﻿<%@ Page Language="C#" Debug="true" %>
<%@ Register TagPrefix="IRL" TagName="DatePicker" Src="DatePicker.ascx" %>
<%@ Register TagPrefix="IRL" TagName="SideBar" Src="SideBar.ascx" %>
<%@ Import Namespace="IRL.Utilities" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.IO" %>


<script runat="server">
    
    public const int CURRENT_MODULE = 51; // ProjectMgt

    int proposalID = 0;
    object connStr;
    bool isUpd;
    bool HasWriteAccess = false;
    bool blnShowMarket;
    
    protected void Page_Load(object src, EventArgs e)
    {
        Security SysAcc = new Security(CURRENT_MODULE);
        // check is authenticate
        SysAcc.Authenticate();
        HasWriteAccess = SysAcc.IsAuthorized(2);
        
        connStr = ConfigurationSettings.AppSettings["sqlConn"];

        // Check connection on Web.config
        if (connStr == null)
        {
            Response.Redirect("unavailable.htm");           
        }
        else
        {
            isUpd = false;

            if (Request.QueryString["pid"] != null)
            {
                try { proposalID = int.Parse(Request.QueryString["pid"]); isUpd = true; }
                catch { proposalID = 0; };
            }

            SideBar1.loadData();
            
            if (IsPostBack)
            {

                saveData();

                    //if (isUpd)
                Response.Redirect("listProposals.aspx");
            }
            else
            {
                loadData();
            }

            // set SID
            SetSID();
        }
    }

    void saveData()
    {
        proposalID = int.Parse(txtProposalID.Text);
        string clientID = cboClientID.SelectedValue;
        string forYear = txtYear.Text;
        string projectName = txtProjectName.Text;
        string projectType = cboProjectType.SelectedValue;
        string researchCategory = cboResearchCategory.SelectedValue;
        string researchType = cboResearchType.SelectedValue;
        decimal cost = Convert.ToDecimal(txtCost.Text);
        string status = cboStatus.SelectedValue;
        object reminderDate = txtReminderDate.CalendarDate;        
        if (reminderDate.ToString() == "")
        {
            reminderDate = DBNull.Value;
        }
        else
        {
            string[] dateElem = reminderDate.ToString().Split('-');
            Array.Reverse(dateElem);            
            //reminderDate = new DateTime(Convert.ToInt32(dateElem[2]), Convert.ToInt32(dateElem[1]), Convert.ToInt32(dateElem[0]));
            reminderDate = DateTime.Parse(String.Join("/", dateElem));
        }
        StringBuilder researchMethodology = new StringBuilder("");
        for (int i = 0; i < chkResearchMethodology.Items.Count - 1; i++)
        {
            if (chkResearchMethodology.Items[i].Selected)
            {
                researchMethodology.Append(chkResearchMethodology.Items[i].Value + ", ");
            }
        }
        if (researchMethodology.Length > 0)
            if (researchMethodology[researchMethodology.Length - 2] == ',')
                researchMethodology.Remove(researchMethodology.Length - 2, 2);
        //researchMethodology = researchMethodology.Substring(0, researchMethodology.Length - 2);
        // market, userid
        string market;
        if (Request.Cookies["office"] == null)
        {
            market = cboMarket.SelectedValue;
        }
        else
        {
            market = Request.Cookies["office"].Value;
        }
        // Call store procedure to save record
        using (SqlConnection conn = new SqlConnection(connStr.ToString()))
        {
            SqlCommand cmd = new SqlCommand("sp_SaveProposal", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@proposalid", SqlDbType.Int).Value = proposalID;
            cmd.Parameters.Add("@clientid", SqlDbType.Int).Value = clientID;
            cmd.Parameters.Add("@year", SqlDbType.Int).Value = forYear;
            cmd.Parameters.Add("@projectname", SqlDbType.NVarChar, 80).Value = projectName;            
            cmd.Parameters.Add("@projecttype", SqlDbType.Int).Value = projectType;
            cmd.Parameters.Add("@researchcategory", SqlDbType.Int).Value = researchCategory;
            cmd.Parameters.Add("@researchtype", SqlDbType.Int).Value = researchType;
            cmd.Parameters.Add("@researchmethodology", SqlDbType.NVarChar, 255).Value = researchMethodology.ToString();
            cmd.Parameters.Add("@costs", SqlDbType.Money).Value = cost;
            cmd.Parameters.Add("@status", SqlDbType.VarChar, 30).Value = status;
            cmd.Parameters.Add("@reminderdate", SqlDbType.DateTime).Value = reminderDate;
            cmd.Parameters.Add("@market", SqlDbType.Int).Value = market;
            cmd.Parameters.Add("@userid", SqlDbType.Int).Value = Request.Cookies["irl_id"].Value;

            conn.Open();
            proposalID = (int)cmd.ExecuteScalar();
            txtProposalID.Text = proposalID.ToString();
            lblSaveStatus.Text = "Data is already saved to the database.<br //><br //>";
            // syncronize record and file location
            if (!isUpd)
            {
                string sid = Session.SessionID;
                string path = ConfigurationSettings.AppSettings["CMS_Path"].ToString();
                string srcPath = path + @"\Temp\" + sid + @"\";
                string destPath = path + @"\project_files\" + proposalID + @"\";

                SqlCommand cmdSync = new SqlCommand("sp_SyncFiles", conn);
                cmdSync.CommandType = CommandType.StoredProcedure;
                cmdSync.Parameters.Add("@pid", SqlDbType.Int).Value = proposalID;
                cmdSync.Parameters.Add("@sid", SqlDbType.VarChar, 64).Value = sid;
                cmdSync.ExecuteNonQuery();
                if (Directory.Exists(srcPath))
                {
                    if (Directory.Exists(destPath))
                    {
                        Directory.Delete(destPath, true);
                    }
                    Directory.Move(srcPath, destPath);
                }
                // send mail
                //Mics.MailSend("chanmann@indochinaresearch.com", "New Proposal is added", "<h1>A new proposal is issued.</h1>");
            }

            // close connection
            conn.Close();
            
        }
    }    

    void loadData()
    {
        DateTime today = DateTime.Today;
        txtYear.Text = today.Year.ToString();
        List.fillList(cboClientID, "SELECT [Company_ID], [Company_Name] FROM [vw_Clients] ORDER BY [Company_Name];");
        List.fillList(cboProjectType, "sp_Select_cms_Lookup 'project_type'");
        List.fillList(cboResearchCategory, "sp_Select_cms_Lookup 'research_category'");
        List.fillList(cboResearchType, "sp_Select_cms_Lookup 'research_type'");
        List.fillChk(chkResearchMethodology, "sp_Select_cms_Lookup 'research_methodology', @ValueOnly=1");
        List.fillList(cboStatus, "sp_Select_cms_Lookup 'proposal_status', @ValueOnly=1");
        // cboMarket
        if (Request.Cookies["office"] == null)
        {
            blnShowMarket = true;
            List.fillList(cboMarket, "SELECT [id], [Name] FROM tbl_IRLs;");
        }
        
        bind_rptFiles();

        // Load data for update form
        if (proposalID > 0)
        {
            using(SqlConnection conn = new SqlConnection(connStr.ToString()))
            {
                SqlCommand cmd = new SqlCommand("SELECT * FROM [cms_Proposals] WHERE [ProposalID]=" + proposalID + ";", conn);
                conn.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    txtProposalID.Text = dr["ProposalID"].ToString();
                    txtYear.Text = dr["ForYear"].ToString();
                    cboClientID.SelectedValue = dr["ClientID"].ToString();
                    txtProjectName.Text = dr["ProjectName"].ToString();
                    cboProjectType.SelectedValue = dr["ProjectType"].ToString();
                    cboResearchCategory.SelectedValue = dr["ResearchCategory"].ToString();
                    string researchMethodology = dr["ResearchMethodology"].ToString();
                    string[] arMethod = researchMethodology.Split(',');
                    foreach (string t in arMethod)
                    {
                        ListItem li = chkResearchMethodology.Items.FindByValue(t.TrimStart());
                        if (li != null)
                        {
                            li.Selected = true;
                        }
                    }
                    txtCost.Text = String.Format("{0:#0.00}", dr["Costs"]);
                    cboStatus.SelectedValue = dr["Status"].ToString();
                    if (dr.GetValue(11) != DBNull.Value)
                    {
                        txtReminderDate.CalendarDate = dr.GetDateTime(11).ToString("dd-MM-yyyy");
                    }
             
                    //foreach (ListItem li in chkResearchMethodology.Items)
                    //{
                    //    if (researchMethodology.IndexOf(li.Text , 0) != -1)
                    //    {
                    //        li.Selected = true;                           
                    //    }
                    //}            
                }
                ConfirmButton.Visible = true;
            }
        }
        else
        {
            int offset = 7;
            txtReminderDate.CalendarDate = today.AddDays(offset).ToString("dd-MM-yyyy");
        }
    }
    
    void bind_rptFiles()
    {
        //object connStr = ConfigurationSettings.AppSettings["sqlConn"];
        using(SqlConnection conn = new SqlConnection(connStr.ToString()))
        {
            SqlCommand cmd = new SqlCommand("SELECT * FROM cms_Files WHERE [ProposalID]="+ proposalID, conn);
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            rptFiles.DataSource = dr;
            rptFiles.DataBind();            
            if (dr.HasRows)
            {
                divFiles.Attributes.Add("class", "files");
            }
            dr.Close();                        
        }
    }

    string showFiles(string ticks, string filename)
    {
        StringBuilder strHtml = new StringBuilder(64);
        strHtml.Append("<div id=\"" + ticks + "\"> " + filename);
        if (HasWriteAccess)
        {
            strHtml.Append(" <a class=\"blue\" href=\"javascript:removeFile('" + ticks + "')\"> Remove</a>");
        }
        strHtml.Append("</div>");

        return strHtml.ToString();
    }
    
    private void SetSID()
    {
        string strScript = "<script language=\"javascript\">";
        strScript += "var sid='"+ Session.SessionID +"';\n";
        strScript += "var pid=" + proposalID + ";\n";
        strScript += "var fileCount=" + rptFiles.Items.Count + ";\n";
        strScript += "<";
        strScript += "/";
        strScript += "script>";
        this.RegisterClientScriptBlock("Init", strScript);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <title>Indochina Research</title>
    <link type="text/css" rel="stylesheet" href="../css/global.css" />
    <link type="text/css" rel="stylesheet" href="css/cms.css" />
    <link href="cal/popcalendar.css" type="text/css" rel="stylesheet" />
    
    <script language="javascript" src="includes/ajax.js"></script>
    <script language="javascript" src="includes/file_functions.js"></script>    
        
    <script language="javascript" src="cal/popcalendar.js"></script>
    <script language="javascript" src="cal/holidays.js"></script>
    <script language="javascript" src="includes/checkDate.js"></script>
    
    <script language="javascript">
        function validateInfo(){            
            var f = document.frmProposal;                                  
            
            //Initialise variables
	        var errorMsg = "";
	        var errorMsgLong = "";
            
            //check Year
            if(f.txtYear.value.length==0){
                errorMsg += "\n\tYear \t\t- You must enter Year";
            }
            
            //check ProjectName
            if(f.txtProjectName.value.length==0){
                errorMsg += "\n\tProject name \t- You must enter Project name";
            }
            
            //check Cost
            if(isNaN(f.txtCost.value) || f.txtCost.value.length==0){
                errorMsg += "\n\tCost \t\t- You must enter Cost";
            }
            
            //check Reminder Date
            if(f.txtReminderDate_txt_Date.value.length>0){
                //alert(isDate(f.txtReminderDate_txt_Date.value));
                if(!isDate(f.txtReminderDate_txt_Date.value)){
                    errorMsg += "\n\tReminder Date \t- Please enter valid date";
                }
            }
                       
            //If there is aproblem with the form then display an error
	        if ((errorMsg != "") || (errorMsgLong != "")){
			        msg = "_______________________________________________________________\n\n";
			        msg += "The form has not been submitted because there are problem(s) with the form.\n";
			        msg += "Please correct the problem(s) and re-submit the form.\n";
			        msg += "_______________________________________________________________\n\n";
			        msg += "The following field(s) need to be corrected: -\n";

			        errorMsg += alert(msg + errorMsg + "\n" + errorMsgLong);
			        return;
	        } 
            
            f.submit();
        }
        
        
        var obj_target;
        function searchClient(target){														
        	
	        obj_target = target;
        	
	        // feature var						
	        //var w=620, h=220;
	        var w=775, h=352;
	        var l=(screen.availWidth-w)/2, t=(screen.availHeight-h)/2;							
        	
	        var newWin = window.open('searchClient.aspx', 'search', 'toolbar=0,status=0,menubar=0,resizable=0,scrollbars=0,width='+ w +',height='+ h +',left='+ l +',top='+ t);
        }
    </script>
        
</head>
<body>
<table width="773" border="0" cellspacing="0" cellpadding="0" align="center">
	<tr>
		<td width="765" height="540" align="center" valign="top" style="border:solid 1px #10147e;" >
			<!-- header -->
			<table border="0" cellpadding="0" cellspacing="0" width="100%">
				<tr bgcolor="#F4F4F9">
					<td colspan="3" align="right" style="padding:10px;">
						<b class="blueL">Client Management System</b>
					</td>
				</tr>
				<tr>
					<td class="wave_l">&nbsp;</td>
					<td><img src="images/wave_logo.jpg" width="107" height="83"></td>
					<td class="wave_r">&nbsp;</td>
				</tr>
				<tr>
					<td colspan="3" style="padding:0 20px;">
						<div style="background-color:#bcb3d5; padding:5px 10px;">
							<span style="float:right">
							    <a class="blue" href="javascript:history.go(-1);">&laquo; Back</a>
							</span>
							<span class="pathmap">
								<a href="default.aspx" >CPanel</a> :: 
								<a href="default2.aspx" >Ops Files</a> :: 
								Add/Update Proposal
						  </span>
						</div>
						<br />
						
						
					</td>
				</tr>
				
			</table>
			
			<!-- body -->
			<form id="frmProposal" method="post" runat="server">
			<table border="0" width="100%" cellspacing="0" cellpadding="0">
				<tr>
					<td align="center" valign="top" style="padding-left:20px;">
						<table align="left" border="0" cellspacing="0" cellpadding="0">
							<tr>
								<td valign="top">
								
									<IRL:SideBar ID="SideBar1" runat="server" />
								
								</td>
								<td width="10"><img src="images/spacer.gif" width="10" height="1" /></td>
								<td valign="top">
									<asp:TextBox ID="txtProposalID" Text="0" Visible="false" runat="server" />
                                    <asp:Label CssClass="orange" ID="lblSaveStatus" runat="server" />
                                    
                                    <table border="0" cellpadding="3" align="center">
                                        <tr>
                                            <td align="right">
                                                Year :
                                            </td>
                                            <td>
                                                <asp:TextBox ID="txtYear" Columns="4" MaxLength="4" runat="server" />&nbsp;&nbsp;*
                                            </td>
                                        </tr>
                                        <tr>
                                            <td width="175" align="right">
                                                Client Name :
                                            </td>
                                            <td nowrap>
                                                <asp:DropDownList ID="cboClientID" runat="server" style="width:245px" />
                                                &nbsp;<a class="blue" href="saveClient.aspx">Add new</a> <span style="cursor: pointer;"
                                                    onclick="searchClient('frmProposal.cboClientID')">
                                                    <img src="images/icon_mini_search.gif" /></span>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td align="right">
                                                Project Name :
                                            </td>
                                            <td>
                                                <asp:TextBox ID="txtProjectName" Columns="40" MaxLength="80" runat="server" />&nbsp;&nbsp;*
                                            </td>
                                        </tr>
                                        <tr>
                                            <td align="right">
                                                Cost :
                                            </td>
                                            <td>
                                                <asp:TextBox CssClass="num" ID="txtCost" runat="server" />
                                                <span class="fldNote">$USD</span>
                                            </td>
                                        </tr>
                                    <% if(blnShowMarket)
                                       { %>
                                        <tr>
                                            <td align="right">
                                                Market :
                                            </td>
                                            <td>
                                                <asp:DropDownList ID="cboMarket" runat="server" />
                                            </td>
                                        </tr>
                                    <% } %>
                                        <tr>
                                            <td align="right">
                                                Project Type :
                                            </td>
                                            <td>
                                                <asp:DropDownList ID="cboProjectType" runat="server" />
                                            </td>
                                        </tr>
                                        <tr>
                                            <td align="right">
                                                Research Category :
                                            </td>
                                            <td>
                                                <asp:DropDownList ID="cboResearchCategory" runat="server" />
                                            </td>
                                        </tr>
                                        <tr>
                                            <td align="right">
                                                Research Type :
                                            </td>
                                            <td>
                                                <asp:DropDownList ID="cboResearchType" runat="server" />
                                            </td>
                                        </tr>
                                        <tr>
                                            <td align="right">
                                                Research Methodology :
                                            </td>
                                            <td>
                                                <asp:CheckBoxList ID="chkResearchMethodology" runat="server" CellPadding="2" RepeatLayout="table"
                                                    RepeatColumns="5" RepeatDirection="vertical" />
                                            </td>
                                        </tr>
                                        <tr>
                                            <td align="right">
                                                Status :
                                            </td>
                                            <td>
                                                <asp:DropDownList ID="cboStatus" runat="server" />
                                            </td>
                                        </tr>
                                        
                                        <tr>
                                            <td align="right">
                                                Reminder Date :
                                            </td>
                                            <td>
                                                <IRL:DatePicker ID="txtReminderDate" runat="server" />
                                            </td>
                                        </tr>
                                        <tr>
                                            <td align="right" valign="top">
                                                Associated Files : </td>
                                            <td width="360">
                                                <div id="divFiles" runat="server">
                                                    <asp:Repeater ID="rptFiles" runat="server">
                                                        <ItemTemplate>
                                                            <%# showFiles(DataBinder.Eval(Container.DataItem, "Ticks").ToString(), DataBinder.Eval(Container.DataItem, "Filename").ToString())%>
                                                            
                                                        </ItemTemplate>
                                                    </asp:Repeater>
                                                </div>
                                                <div id="divAddFile" runat="server">
                                                    <a class="blue" href="javascript:showCtrl();">Add file</a></div>
                                                <div id="divCtrl" class="hidden">
                                                    <iframe name="fraUpload" frameborder="0" scrolling="no" width="100%" height="22"
                                                        src="add_file.aspx?pid=<%=proposalID %>"></iframe>
                                                </div>
                                                <div id="divStat" class="hidden">
                                                </div>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>&nbsp;
                                                
                                            </td>
                                            <td>&nbsp;
                                                
                                            </td>
                                        </tr>
                                        <tr>
                                            <td align="right">&nbsp;
                                                
                                            </td>
                                            <td>                                        
                                                <table id="SaveButton" border="0" cellpadding="2" cellspacing="0" runat="server">
                                                    <tr>
                                                        <td width="128">
                                                            <a class="cmd" href="javascript:validateInfo();">Save Proposal</a></td>
                                                        <td width="5">&nbsp;</td>
                                                        <td width="60" id="ConfirmButton" visible="false" runat="server">
                                                            <a class="cmd" href="saveProject.aspx?pid=<%=proposalID %>&confirm=1">Confirm</a></td>
                                                        <td width="5">&nbsp;</td>
                                                        <td width="80">
                                                            <a class="cmd" href="javascript:history.go(-1);">Cancel</a></td>
                                                    </tr>
                                                </table>
                                            </td>
                                        </tr>
                                    </table>
                                    
								</td>
							</tr>
						</table>
					</td>
				</tr>
			</table><br /><br />
			</form>
			
		</td>
		
		<td width="6" class="rightShadow" valign="top">
			<img src="images/white.gif" width="6" height="6" /></td>
	</tr>
	
	<!-- bottom shadow -->
	<tr>
		<td height="6" class="bottomShadow">
			<img src="images/white.gif" width="6" height="6" /></td>
		
		<td width="6" height="6">
			<img src="images/shadow_corner.gif" width="6" height="6" /></td>
	</tr>
</table>


</body>
</html>
